package com.yinxing.framework.system;

import ch.qos.logback.core.OutputStreamAppender;
import com.yinxing.netty.utils.ExtPushMessage;
import com.yinxing.netty.utils.ServerUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class SocketAppender extends OutputStreamAppender {

    @Override
    public void start() {

        // 管道读取流
        PipedInputStream pipedInputStream = new PipedInputStream();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(pipedInputStream, StandardCharsets.UTF_8));

        // 管道写入流
        PipedOutputStream pipedOutputStream = new PipedOutputStream();

        try {
            // 写入读取管道链接
            pipedOutputStream.connect(pipedInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 设置输出流到Appender
        super.setOutputStream(pipedOutputStream);

        // 子线程开始从管道流读取数据
        Thread thread = new Thread(() -> {
            String line = null;
            while (true) {
                try {
                    line = bufferedReader.readLine();
                } catch (IOException e) {
                    // e.printStackTrace();
                }
                if (line != null) {
                    line = line.replace("DEBUG", "<span style='color:blue;'>DEBUG</span>");
                    line = line.replace("INFO", "<span style='color:green;'>INFO</span>");
                    line = line.replace("WARN", "<span style='color:orange;'>WARN</span>");
                    line = line.replace("ERROR", "<span style='color:red;'>ERROR</span>");
                    ExtPushMessage message = new ExtPushMessage(ExtPushMessage.MessageType.SYS_LOG);
                    message.put("data", line);
                    ServerUtils.sendMessageToAll(message);
                }
            }
        });

        thread.setDaemon(Boolean.TRUE);
        thread.setName("socket-log");
        thread.start();

        super.start();
    }
}
